package net.qiqbframework.messaging.intercepting;

import net.qiqbframework.messaging.Message;

import javax.annotation.Nonnull;
import java.util.Collections;
import java.util.List;
import java.util.function.BiFunction;

/**
 * 允许在发送消息之前截获和修改消息的拦截器。此拦截器提供了一种非常早期的方法来更改或拒绝消息，甚至在创建任何工作单元之前
 *
 */
public interface MessageDispatchInterceptor<T extends Message<?>> {

    /**
     * Invoked each time a message is about to be dispatched. The given {@code message} represents the message being
     * dispatched.
     *
     * @param message The message intended to be dispatched
     * @return the message to dispatch
     */
    @Nonnull
    default T handle(@Nonnull T message) {
        return handle(Collections.singletonList(message)).apply(0, message);
    }

    /**
     * Apply this interceptor to the given list of {@code messages}. This method returns a function that can be invoked
     * to obtain a modified version of messages at each position in the list.
     *
     * @param messages The Messages to pre-process
     * @return a function that processes messages based on their position in the list
     */
    @Nonnull
    BiFunction<Integer, T, T> handle(@Nonnull List<? extends T> messages);

}
